package com.foreknow.demo16;


import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Manager {
    /**
     * 向文件中写数据
     */
    public void writeFile(List<Student> list) {
        // BufferedWriter FileWriter
        // 遍历list集合，每循环一次就要将一个学生的信息写到目标文件中
        // 向目标文件中写入是字符串 student.getId() + " " + student.getName()
        // 关闭流
        try {
            FileWriter fw = new FileWriter("student.txt");
            BufferedWriter bw = new BufferedWriter(fw);
            Iterator<Student> it = list.iterator();
            while (it.hasNext()) {
                Student stu = it.next();
                String str = stu.getSid() + " " + stu.getName() + " " + stu.getEmail() +
                        " " + stu.getAddress() + " " + stu.getPhone();
                bw.write(str);
                //换行
                bw.newLine();
                bw.flush();
            }
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从文件中读取数据
     */
    public List<Student> readFile(String fileName) {
        //BufferedReader  FileReader
        //读取数据 br.readLine();  100 fender1 fender@163.com neu 1212121212
        //拆分字符串 将拆分之后的数据保存到数组中
        //将拆分的数据保存到Student对象中
        //再将这个对象保存到List集合中
        //最后返回list集合
        List<Student> list = new ArrayList<>();
        try {
            FileReader fr = new FileReader(fileName);
            BufferedReader br = new BufferedReader(fr);
            String temp;
            while ((temp = br.readLine()) != null) {
                String[] str = temp.split(" ");

                Student student = new Student();
                student.setSid(Integer.parseInt(str[0]));
                student.setName(str[1]);
                student.setEmail(str[2]);
                student.setAddress(str[3]);
                student.setPhone(str[4]);

                list.add(student);
            }
            br.close();
            fr.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}







